package cn.fl.project.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;

import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.DateUtils;
import cn.cmm.base.framework.utils.DecimalUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.customer.vo.CstBscInfoVO;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.project.condition.PrjCstOwnVehicleQueryCondition;
import cn.fl.project.service.IPrjBscInfoService;
import cn.fl.project.service.IPrjCstOwnVehicleService;
import cn.fl.project.vo.PrjCstOwnVehicleVO;
import cn.fl.system.constant.SysLogConstant;
import net.sf.json.JSONArray;

/**
 * @Description: 客户自有运营车辆信息表 控制层
 */
@Controller
@RequestMapping("/project/prjcstownvehicle")
public class PrjCstOwnVehicleController extends BaseController {
	private static final Logger logger = LoggerFactory.getLogger(PrjCstOwnVehicleController.class);


	/**
	 * PrjCstOwnVehicle 服务层BEAN
	 */
	@Autowired
	private IPrjCstOwnVehicleService prjCstOwnVehicleService;
	@Autowired
	private IPrjBscInfoService prjBscInfoService;
	
	/**
	 * 到列表页面
	 */
	@RequestMapping(value = "/toListPage.do", method = { RequestMethod.GET})
	public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
		String prjId = request.getParameter("prjId");//项目ID
		String detailFlag = request.getParameter("detailFlag");
		CstBscInfoVO cstBscInfoVO = null; 
		String cstType = "";
		Long cstId=null;
		if(StringUtils.isNotBlank(prjId)){
			cstBscInfoVO = prjBscInfoService.getCstTypByPrjId(Long.valueOf(prjId));
			if(null!=cstBscInfoVO){
				 cstType = cstBscInfoVO.getCstTypCd();
				 cstId= cstBscInfoVO.getId();
			}
		}
		ModelAndView view = new ModelAndView("project/prjcstownvehicle/prjCstOwnVehicleList");
		BaseLogUtils.info(logger, "toListPage", "跳转到列表页面.", CurrentThreadContext.getCurrentUserName());
		view.addObject("prjId", prjId);
		view.addObject("cstType",cstType);
		view.addObject("cstId", cstId);
		view.addObject("detailFlag", detailFlag);
		return view;
	}

	/**
	 * 到自有车辆添加页面
	 */
	@RequestMapping(value = "/toAddPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toEquiAddPage(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView("project/prjcstownvehicle/prjCstOwnVehicleAdd");
		String cstType = request.getParameter("cstType");
		String prjId = request.getParameter("prjId");
		String cstId = request.getParameter("cstId");
		String id = request.getParameter("id");
		PrjCstOwnVehicleVO vehicle = null; 
		if(StringUtils.isNotBlank(id)){
			vehicle = prjCstOwnVehicleService.selectById(Long.valueOf(id));
		}
		view.addObject("prjId", prjId);
		view.addObject("cstType", cstType);
		view.addObject("cstId", cstId);
		view.addObject("vehicle", vehicle);
		BaseLogUtils.info(logger, "toAddPage", "跳转到自有车辆添加页面.", CurrentThreadContext.getCurrentUserName());
		return view;
	}
	/**
	 * 到详细页面
	 */
	@RequestMapping(value = "/toDetailPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");
		PrjCstOwnVehicleVO vehicle = null; 
		if(StringUtils.isNotBlank(id)){
			vehicle = prjCstOwnVehicleService.selectById(Long.valueOf(id));
		}
		ModelAndView view = new ModelAndView("project/prjcstownvehicle/prjCstOwnVehicleDetail");
		view.addObject("id", id);
		view.addObject("vehicle", vehicle);
		BaseLogUtils.info(logger, "toModifyPage", "跳转到详细页面.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		return view;
	}

	/**
	 * 初始化列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initList(HttpServletRequest request, HttpServletResponse response) {
		String prjId = request.getParameter("prjId");
		String cstId = request.getParameter("cstId");
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize"); 
		Pager pager  = null;
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		try {
			Pager page = new Pager();
			if (StringUtils.isNotEmpty(currentPage)) {
				page.setCurrentPage(Integer.parseInt(currentPage));
			}

			if (StringUtils.isNotEmpty(pageSize)) {
				page.setEveryPage(Integer.parseInt(pageSize));
			}
			if(StringUtils.isNotBlank(prjId)&&StringUtils.isNotBlank(cstId)){
				PrjCstOwnVehicleQueryCondition qc = new PrjCstOwnVehicleQueryCondition();
				qc.setCstId(Long.valueOf(cstId));
				qc.setPrjId(Long.valueOf(prjId));
				page.setCondition(qc);
				pager = this.prjCstOwnVehicleService.searchListPage(page);
			}
			BaseLogUtils.info(logger, "initList", "获取数据.", CurrentThreadContext.getCurrentUserName());
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "initList", "获取失败."+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "initList", "获取失败"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		List<PrjCstOwnVehicleVO> list = (List<PrjCstOwnVehicleVO>) pager.getResultList();
		ListPageVO<PrjCstOwnVehicleVO> listPage = new ListPageVO<PrjCstOwnVehicleVO>(list, pager.getTotalCount());
		BaseLogUtils.info(logger, "initList", "查询数据完成. DATA:" + JSONObject.toJSONString(listPage), CurrentThreadContext.getCurrentUserName());
		return listPage;
	}

	/**
	 * 删除数据
	 */
	@RequestMapping(value = "/removeByIds.do", method = {RequestMethod.POST })
	@ResponseBody
	public DataResultVO removeByIds(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String ids = request.getParameter("ids");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
		if(StringUtils.isEmpty(ids)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			return result;
		}
		List<Long> idList = new ArrayList<Long>();
		JSONArray idsArray =JSONArray.fromObject(ids);
		for (Object object : idsArray) {
			idList.add(Long.valueOf(object.toString()));
		}
		try {
			this.prjCstOwnVehicleService.removeByIds(idList);
			BaseLogUtils.info(logger, "removeByIds", "删除数据.[ids="+ids+"]", CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "removeByIds", "删除数据失败.[ids="+ids+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "removeByIds", "删除数据失败.[id="+ids+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 得到一条记录
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getById.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.error(logger, "getById", "获取数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		
		try {
			PrjCstOwnVehicleVO vo = this.prjCstOwnVehicleService.selectById(Long.valueOf(id));
			if(null == vo){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
				BaseLogUtils.info(logger, "getById", "获取数据,数据不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			}
			result.setData(vo);
			BaseLogUtils.info(logger, "getById", "获取数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "getById", "获取失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "getById", "获取失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 新增
	 */
	@RequestMapping(value = "/add.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object add(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String rptId = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
		PrjCstOwnVehicleVO entity = null;
		Long id = null;
		try {
			PrjCstOwnVehicleVO prjCstOwnVehicleVO = getPrjCstOwnVehicleParam(request);
			if(StringUtils.isNotBlank(rptId)){
				//修改客户自有运营车辆信息
				prjCstOwnVehicleVO.setId(Long.valueOf(rptId));
				this.prjCstOwnVehicleService.modify(prjCstOwnVehicleVO);
				result.setSuccess(BaseConstant.IS_YESNO_YES);
				result.setInfo(SysLogConstant.LOG_CMM_UPDATE_SUCC);
				id=Long.valueOf(rptId);
			}else{
				//添加客户自有运营车辆信息
				prjCstOwnVehicleVO.setCrtTm(new Date());
				prjCstOwnVehicleVO.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
				prjCstOwnVehicleVO.setIsDel(BaseConstant.IS_YESNO_NO);
				 id = this.prjCstOwnVehicleService.add(prjCstOwnVehicleVO);
			}
			result.setData(id);
			BaseLogUtils.info(logger, "add", "新增数据.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "add", "新增数据失败.DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "add", "新增数据失败.DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}

	private PrjCstOwnVehicleVO getPrjCstOwnVehicleParam(HttpServletRequest request) {
		PrjCstOwnVehicleVO vehicle = new PrjCstOwnVehicleVO();
		String prjId = request.getParameter("prjId");//项目ID
		String cstId = request.getParameter("cstId");//客户ID 
		String buyDt = request.getParameter("buyDt");//购买时间
		String brNm = request.getParameter("brNm");//品牌
		String qty = request.getParameter("qty");//数量
		String buyPrc = request.getParameter("buyPrc");//购买价格（万元）
		String loanBlc = request.getParameter("loanBlc");// 贷款余额（万元)
		String cryTng = request.getParameter("cryTng");//运载吨位
		String psgNum = request.getParameter("psgNum");//客车载客数（仅客车）
		if(StringUtils.isNotBlank(prjId)){
			vehicle.setPrjId(Long.valueOf(prjId));
		}
		if(StringUtils.isNotBlank(cstId)){
			vehicle.setCstId(Long.valueOf(cstId));
		}
		if(StringUtils.isNotBlank(buyDt)){
			vehicle.setBuyDt(DateUtils.formatStringToDate(buyDt, DateUtils.YYYY_MM_DD));
		}
		if(StringUtils.isNotBlank(brNm)){
			vehicle.setBrNm(brNm);
		}
		if(StringUtils.isNotBlank(qty)){
			vehicle.setQty(Integer.valueOf(qty));
		}
		if(StringUtils.isNotBlank(buyPrc)){
			vehicle.setBuyPrc(DecimalUtils.convertYuanToFen(Double.valueOf(buyPrc)).doubleValue());
		}
		if(StringUtils.isNotBlank(loanBlc)){
			vehicle.setLoanBlc(DecimalUtils.convertYuanToFen(Double.valueOf(loanBlc)).doubleValue());
		}
		if(StringUtils.isNotBlank(cryTng)){
			vehicle.setCryTng(Long.valueOf(cryTng));
		}
		if(StringUtils.isNotBlank(psgNum)){
			vehicle.setPsgNum(Integer.parseInt(psgNum));
		}
		return vehicle;
	}

	/**
	 * 修改
	 */
	@RequestMapping(value = "/modify.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object modify(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		String name = request.getParameter("name");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "modify", "修改数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		PrjCstOwnVehicleVO entity = null;
		try {
			entity = new PrjCstOwnVehicleVO();
			entity.setId(Long.valueOf(id));
			//entity.setName(name);
			//TODO ADD PARAM
			boolean success = this.prjCstOwnVehicleService.modify(entity);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
				BaseLogUtils.info(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
			}
			BaseLogUtils.info(logger, "modify", "修改成功.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}
}

